package cn.tedu.mall.book.service.impl;

import cn.tedu.mall.book.entity.Product;
import cn.tedu.mall.book.ex.ServiceException;
import cn.tedu.mall.book.mapper.CategoryMapper;
import cn.tedu.mall.book.mapper.ProductMapper;
import cn.tedu.mall.book.pojo.dto.ProductAddNewDTO;
import cn.tedu.mall.book.pojo.dto.ProductUpdateDTO;
import cn.tedu.mall.book.pojo.vo.CategorySimpleVO;
import cn.tedu.mall.book.pojo.vo.ProductSimpleVO;
import cn.tedu.mall.book.pojo.vo.ProductDetailVO;
import cn.tedu.mall.book.service.IProductService;
import cn.tedu.mall.book.web.JsonPage;
import cn.tedu.mall.book.web.State;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author zxjun
 * @date 2022/6/10 20:36
 */
@Service
@Slf4j
public class ProductServiceImpl implements IProductService {

    @Autowired
    ProductMapper productMapper;
    @Autowired
    CategoryMapper categoryMapper;

    /**
     *
     * @param productAddNewDTO
     * @return
     */
    @Override
    public void addNewProduct(ProductAddNewDTO productAddNewDTO) {
        //如果商品名称存在,抛出异常
        String name=productAddNewDTO.getName();
        //从数据库查询是否存在同名商品
        ProductSimpleVO productSimpleVO=productMapper.selectProductByName(name);
        if (productSimpleVO!=null){
            throw new ServiceException(State.ERR_NAME_DUPLICATE,"商品名称重复，请重新提交");
        }
        //创建一个Product对象
        Product product=new Product();
        //将productAddNewDTO的值给productDetailsDTO
        BeanUtils.copyProperties(productAddNewDTO,product);
        Date date=new Date();
        LocalDate localDate=LocalDate.now();
        product.setAddTime(localDate);//设置上架时间
        product.setSaleCount(0);//设置销量
        product.setGmtCreate(LocalDateTime.now());//数据创建时间
        product.setGmtModified(LocalDateTime.now());//数据修改时间
        productMapper.insert(product);
    }

    @Override
    public void updateById(ProductUpdateDTO productUpdate) {
        Long id = productUpdate.getId();
        ProductDetailVO product = productMapper.getById(id);
        System.out.println(product);
        if (product==null){
            throw new ServiceException(State.ERR_NOT_FOUND,"要修改的商品不存在");
        }
        productUpdate.setGmtModified(LocalDateTime.now());
        productMapper.updateById(productUpdate);
    }

    @Override
    public void deleteById(Long id) {
        ProductDetailVO product = productMapper.getById(id);
        if (product==null){
            throw new ServiceException(State.ERR_NOT_FOUND,"要删除的商品不存在");
        }
        productMapper.deleteById(id);
    }

    @Override
    public JsonPage<ProductSimpleVO> getList(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<ProductSimpleVO> list = productMapper.getList();
        for (ProductSimpleVO productSimpleVO : list) {
            productSimpleVO.setIseditor(false);
        }
        PageInfo<ProductSimpleVO> pageInfo = new PageInfo<>(list);
        return JsonPage.restPage(pageInfo);
    }

    /**
     * 根据商品id查询商品详细信息
     * @param id
     * @return
     */
    @Override
    public ProductDetailVO getById(Long id) {
        ProductDetailVO productVO = productMapper.getById(id);
        return productVO;
    }

    /**
     * 首页新书首发业务
     * @return
     */
    @Override
    public List<ProductSimpleVO> getBookForNewStart() {
        List<ProductSimpleVO> bookForNewStart = productMapper.getBookForNewStart();
        constraintNameLength(bookForNewStart,7);
        // bookForNewStart.forEach(System.out::println);
        return bookForNewStart;
    }

    /**
     * 首页精品推荐业务
     * @return
     */
    @Override
    public List<ProductSimpleVO> getBookForRecommend() {
        List<ProductSimpleVO> bookForRecommend = productMapper.getBookForRecommend();
        constraintNameLength(bookForRecommend,7);
        return bookForRecommend;
    }

    /**
     * 按id分类进行查询
     * @param categoryId
     * @return
     */
    @Override
    public List<ProductSimpleVO> getProductsByCategoryId(Integer categoryId) {
        return getProductById(categoryId);
    }


    /**
     *
     * @param categoryId
     * @param index
     * @return
     */
    @Override
    public List<ProductSimpleVO> getProductsByCategoryChildrenIdOrderly(Integer categoryId,String index) {
        List<ProductSimpleVO> products = getProductById(categoryId);
        if ("1".equals(index)){
            //综合排序
            return products;
        }else if("2".equals(index)){
            //销量降序
            Collections.sort(products,(p1,p2)->p2.getSaleCount()-p1.getSaleCount());
            return products;
        }else if("3-1".equals(index)){
            //价格升序
            Collections.sort(products, Comparator.comparingDouble(ProductSimpleVO::getDiscountPrice));
            return products;
        }else if("3-2".equals(index)){
            //价格降序
            Collections.sort(products, (o1,o2) ->{
                    if (o1.getDiscountPrice()<o2.getDiscountPrice()){
                        return 1;
                    }else {
                        return -1;
                    }
            });
            return products;
        }else{
            //最新
            Collections.sort(products,(o1,o2)-> {
                    if (o1.getAddTime().before(o2.getAddTime())){
                        return -1;
                    }else {
                        return 1;
                    }
            });
            return products;
        }
    }

    @Override
    public List<ProductSimpleVO> getProductsBySearch(String keyWord) {
        List<ProductSimpleVO> productsBySearch = productMapper.getProductsBySearch(keyWord);
        constraintNameLength(productsBySearch,12);
        return productsBySearch;
    }


    /**
     *
     * @param keyWord
     * @param index
     * @return
     */
    @Override
    public List<ProductSimpleVO> getProductsBySearchOrderly(String keyWord,String index) {
        List<ProductSimpleVO> products = productMapper.getProductsBySearch(keyWord);
        constraintNameLength(products,12);
        if ("1".equals(index)){
            //综合排序
            return products;
        }else if("2".equals(index)){
            //销量降序
            Collections.sort(products,(p1,p2)->p2.getSaleCount()-p1.getSaleCount());
            return products;
        }else if("3-1".equals(index)){
            //价格升序
            Collections.sort(products, Comparator.comparingDouble(ProductSimpleVO::getDiscountPrice));
            return products;
        }else if("3-2".equals(index)){
            //价格降序
            Collections.sort(products, (o1,o2) ->{
                if (o1.getDiscountPrice()<o2.getDiscountPrice()){
                    return 1;
                }else {
                    return -1;
                }
            });
            return products;
        }else{
            //最新
            Collections.sort(products,(o1,o2)-> {
                if (o1.getAddTime().before(o2.getAddTime())){
                    return -1;
                }else {
                    return 1;
                }
            });
            return products;
        }
    }


    /**
     *
     * @return
     */
    @Override
    public List<ProductSimpleVO> getBookForNewBookTop() {
        List<ProductSimpleVO> bookForNewBookTop = productMapper.getBookForNewBookTop();
        constraintNameLength(bookForNewBookTop,3);
        return bookForNewBookTop;
    }


    /**
     *
     * @return
     */
    @Override
    public List<ProductSimpleVO> getBookForBestSellerTop() {
        List<ProductSimpleVO> bookForBestSellerTop = productMapper.getBookForBestSellerTop();
        constraintNameLength(bookForBestSellerTop,3);
        return bookForBestSellerTop;
    }



    /**
     * 约束书名长度
     * @param list 简单商品集合
     * @param length 要约束的长度
     */
    private void constraintNameLength(List<ProductSimpleVO> list,int length){
        for (ProductSimpleVO productSimpleVO : list) {
            String name = productSimpleVO.getName();
            if (name.length() > length) {
                name = name.substring(0, length) + "...";
                productSimpleVO.setName(name);
            }
        }
    }


    /**
     *
     * @param id
     * @return
     */
    private List<ProductSimpleVO> getProductById(Integer id){
        // 根据id获取分类信息
        CategorySimpleVO categorySimpleVO = categoryMapper.getCategorySimpleById(id);
        // 判断获取到的分类信息是否为null
        if (categorySimpleVO ==null) {
            // 是:抛出异常
            throw new ServiceException(State.ERR_NOT_FOUND,"获取分类信息失败,分类id无效");
        }
        // 否:判断该分类是否不为父级分类
        if (categorySimpleVO.getIsParent()!=1) {
            // 是:得到商品并返回
            List<ProductSimpleVO> productsByCategoryChildrenId = productMapper.getProductsByCategoryChildrenId(id);
            constraintNameLength(productsByCategoryChildrenId,12);
            return productsByCategoryChildrenId;
        }else {
            // 否:得到子级分类,并根据子级分类id获取商品并返回
            List<CategorySimpleVO> childrenCategories = categoryMapper.getChildrenCategoryByParentId(id);
            List<ProductSimpleVO> productSimpleVOList = new ArrayList<>();
            for (CategorySimpleVO childrenCategory : childrenCategories) {
                productSimpleVOList.addAll(productMapper.getProductsByCategoryChildrenId(childrenCategory.getId()));
            }
            constraintNameLength(productSimpleVOList,12);
            return productSimpleVOList;
        }
    }

}
